package com.summer.study.leetcode.thread.sequence_114;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther: 杨杰
 * @date: 2019/7/25 10:46
 * @description:
 */
public class ReentrantLockDemo {

    private ReentrantLock lock = new ReentrantLock();

    private int state = 1;

    private Condition c1 = lock.newCondition();

    private Condition c2 = lock.newCondition();

    private Condition c3 = lock.newCondition();

    public void first(Runnable printFirst) throws InterruptedException {
        lock.lock();
        try {
            while (state != 1) {
                c1.await();
            }
            printFirst.run();
            state++;
            c2.signal();

        } finally {
            lock.unlock();
        }

    }

    public void second(Runnable printSecond) throws InterruptedException {
        lock.lock();
        try {
            while (state != 2) {
                c2.await();
            }
            printSecond.run();
            state++;
            c3.signal();
        } finally {
            lock.unlock();
        }

    }

    public void third(Runnable printThird) throws InterruptedException {
        lock.lock();
        try {
            while (state != 3) {
                c3.await();
            }
            printThird.run();
        } finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        ReentrantLockDemo demo = new ReentrantLockDemo();
        Foo foo = new Foo();

        demo.first(new Thread(() -> {
            foo.one();
        }));
        demo.second(new Thread(() -> {
            foo.two();
        }));
        demo.third(new Thread(() -> {
            foo.three();
        }));
    }
}
